"""
视频评论数据采集Web服务
提供API接口和前端展示功能
"""

from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit
import threading
import glob
import csv
import os

from comment_crawler import VideoCommentCrawler

# 初始化Flask应用
app = Flask(__name__)
app.config['SECRET_KEY'] = 'video_comment_web_2024'

# 初始化WebSocket
socketio = SocketIO(app, cors_allowed_origins="*")


@app.route('/')
def index():
    """主页面"""
    return render_template('index.html')


@app.route('/api/crawl', methods=['POST'])
def start_crawl():
    """API: 开始数据采集"""
    try:
        data = request.get_json()
        video_url = data.get('video_url', '').strip()
        
        if not video_url:
            return jsonify({'error': '请输入视频URL'}), 400
        
        print(f"收到采集请求: {video_url}")
        
        # 创建采集器并执行
        crawler = VideoCommentCrawler(video_url)
        result = crawler.start_collection()
        
        return jsonify(result)
        
    except Exception as e:
        print(f"API异常: {str(e)}")
        return jsonify({'error': str(e)}), 500


@socketio.on('start_crawl')
def handle_crawl_request(data):
    """WebSocket: 处理采集请求（支持实时进度）"""
    video_url = data.get('video_url', '').strip()
    min_likes = data.get('min_likes', 0)  # 最小点赞数
    min_replies = data.get('min_replies', 0)  # 最小回复数
    
    if not video_url:
        emit('crawl_error', {'error': '请输入视频URL'})
        return
    
    # 获取当前会话ID
    session_id = request.sid
    
    def crawl_worker():
        try:
            socketio.emit('crawl_progress', {
                'status': '正在初始化数据采集器...', 
                'progress': 10
            }, room=session_id)
            
            # 创建采集器并设置过滤条件
            crawler = VideoCommentCrawler(video_url, min_likes=min_likes, min_replies=min_replies)
            
            socketio.emit('crawl_progress', {
                'status': '正在连接目标服务器...', 
                'progress': 30
            }, room=session_id)
            
            result = crawler.start_collection()
            
            socketio.emit('crawl_progress', {
                'status': '正在处理和保存数据...', 
                'progress': 90
            }, room=session_id)
            
            if result['success']:
                socketio.emit('crawl_complete', {
                    'success': True,
                    'total_comments': result['total_comments'],
                    'filtered_comments': result.get('filtered_comments', 0),
                    'output_file': result['output_file'],
                    'data': result['data']
                }, room=session_id)
            else:
                socketio.emit('crawl_error', {'error': result['error']}, room=session_id)
                
        except Exception as e:
            socketio.emit('crawl_error', {'error': str(e)}, room=session_id)
    
    # 启动后台线程
    thread = threading.Thread(target=crawl_worker)
    thread.daemon = True
    thread.start()
    
    emit('crawl_started', {'message': '开始数据采集...'})


@app.route('/api/latest_data')
def get_latest_data():
    """获取最新采集的数据用于前端展示"""
    try:
        # 查找最新的CSV文件
        csv_files = glob.glob('comments_data_*.csv')
        if not csv_files:
            return jsonify({'comments': [], 'wordcloud_data': []})
        
        # 按文件修改时间排序，获取最新的
        latest_file = max(csv_files, key=os.path.getmtime)
        
        # 读取CSV数据
        comments = []
        with open(latest_file, 'r', encoding='utf-8-sig') as file:
            reader = csv.DictReader(file)
            for row in reader:
                comments.append({
                    'content': row['content'],
                    'likes': int(row['likes']) if row['likes'].isdigit() else 0,
                    'replies': int(row['replies']) if row['replies'].isdigit() else 0
                })
        
        return jsonify({
            'comments': comments,
            'total': len(comments),
            'source_file': latest_file
        })
        
    except Exception as e:
        print(f"获取数据失败: {str(e)}")
        return jsonify({'comments': []}), 500


if __name__ == '__main__':
    print("🚀 视频评论数据采集Web服务启动中...")
    print("📡 访问地址: http://localhost:5000")
    
    # 启动应用
    socketio.run(app, host='0.0.0.0', port=5000, debug=True) 